package com.intel.two.exception;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @date 2022/9/29
 * @desc   进行页面跳转的全局异常处理的方式   开发中不常用
 */
public class CustomExceptionResolver implements HandlerExceptionResolver {
    /**
     * 异常解析器：主体逻辑
     * 执行时刻：当handler中抛出异常时，会执行：捕获异常，并可以跳到错误页面
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        CustomerException customerException = null;
        ModelAndView modelAndView = new ModelAndView();

        ex.printStackTrace();
        if(ex instanceof CustomerException){
            //预料中异常
             customerException = (CustomerException) ex;
             modelAndView.addObject("error",customerException.getMessage());
        }else{

            //预料之外异常
            modelAndView.addObject("error","对不起，服务器繁忙，请联系管理员");
        }

        modelAndView.setViewName("page/error");

        return modelAndView;
    }
}
